package san.service.article;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.queryParser.ParseException;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import san.dao.LuceneTextQuery;
import san.dao.article.ArticleDao;
import san.dao.article.ArticleItemDao;
import san.entity.article.Article;
import san.entity.article.ArticleItem;
import com.utils.CollectionUtils;
import com.utils.Page;
import com.utils.itext.PdfGenerate;
import com.utils.itext.PdfGenerate.PdfRow;
import com.utils.poi.ExcelGenerate;
import com.utils.poi.ExcelGenerate.Excel;
import com.utils.poi.ExcelGenerate.ExcelCell;
import com.utils.poi.ExcelGenerate.ExcelRow;
import com.utils.web.WebUtils;

/**
 * Article service
 */
@Service
@Transactional
public class ArticleService {
	@Autowired
	private ArticleDao articleDao;
	@Autowired
	private ArticleItemDao articleItemDao;
	@Autowired
	private LuceneTextQuery luceneTextQuery;

	/*
	 * 文章类型列表 分页
	 */
	@Transactional(readOnly = true)
	public Page getPageForArticle(Page page) throws Exception {
		page.setAutoCount(false);
		page = articleDao.getAllArticleAndCount(page);
		return page;
	}

	/*
	 * 获得某一类型的所有文章(分页)
	 */
	@Transactional(readOnly = true)
	public Page<ArticleItem> getAllArticleForPage(Page<ArticleItem> page, String articleid)
			throws Exception {
		String hql = "from ArticleItem o where o.article.id=?";
		return articleItemDao.findPage(page, hql, articleid);
	}

	/*
	 * 获得某一类型的所有文章(分页) 模糊查询
	 */
	@Transactional(readOnly = true)
	public Page<ArticleItem> getAllArticleForPage(Page<ArticleItem> page, String hql, String articleid)
			throws Exception {
		hql = hql + " and o.article.id=?";
		return articleItemDao.findPage(page, hql, articleid);
	}

	/*
	 * 删除一篇文章
	 */
	public void removeArticleItem(String articleitemid) throws Exception {
		ArticleItem articleItem = (ArticleItem) articleItemDao.get(articleitemid);
		articleItemDao.delete(articleItem);
	}

	/*
	 * 根据ID得到某一篇文章
	 */
	@Transactional(readOnly = true)
	public ArticleItem getArticleItemById(String articleItemId)
			throws Exception {
		ArticleItem articleItem = (ArticleItem) articleItemDao.get(articleItemId);
		return articleItem;
	}

	/*
	 * 根据ID得到某一类型
	 */
	@Transactional(readOnly = true)
	public Article getArticleById(String articleid) throws Exception {
		Article article = (Article) articleDao.get(articleid);
		return article;
	}

	/*
	 * 添加文章类型
	 */
	public Article addArticle(String articletype) throws Exception {
		if (StringUtils.isNotBlank(articletype)) {
			Article articletemp = (Article) articleDao.findUniqueBy("articletype", articletype);
			// 判断文章类型是否重复
			if (articletemp != null) {
				return null;
			} else {
				Article article = new Article();
				article.setArticleItems(new ArrayList<ArticleItem>());
				article.setArticletype(articletype);
				articleDao.save(article);
				return article;
			}
		} else {
			return null;
		}
	}

	/*
	 * 添加一篇文章
	 */
	public void addArticleItem(String articleid, ArticleItem articleitem) {
		Article article = (Article) articleDao.get(articleid);
		article.addArticleItem(articleitem);
		articleDao.save(article);
	}

	/*
	 * 修改一篇文章
	 */
	public void updateArticleItem(String articleid, ArticleItem articleitem) {
		Article article = (Article) articleDao.get(articleid);
		articleitem.setArticle(article);
		articleItemDao.save(articleitem);
	}

	/*
	 * 修改文章类型
	 */
	public void updateArticleType(String articleid, String text)
			throws Exception {
		Article article = (Article) articleDao.get(articleid);
		article.setArticletype(text);
		articleDao.save(article);
	}

	/*
	 * 删除文章类型，对应文章全部删除
	 */
	public void removeArticleType(String articleid) throws Exception {
		articleDao.delete(articleid);
	}

	/*
	 * 获得所有类型文章，供下拉列表用
	 */
	@Transactional(readOnly = true)
	public List<Article> getListMapAllArticle() throws Exception {
		String hql = "from Article";
		List<Article> list = articleDao.find(hql);
		return list;
	}

	/*
	 * 全文检索
	 */
	@SuppressWarnings("unchecked")
	public List<ArticleItem> getText(String text) throws ParseException {
		 return luceneTextQuery.findByFullText(new String[] {"title","content","author"}, text, ArticleItem.class);
	}
	/*
	 * 
	 */
	public Page<ArticleItem> getReportPage(Page<ArticleItem> page, ArticleItem articleItem,
			HttpServletRequest request) throws Exception {
		String hql = CollectionUtils.getHql(request, "articleItem", articleItem);
		return articleItemDao.findPageByOrder(page, hql);
	}
	
	/*
	 * 生成Excel报表
	 */
	public void getExcel(Page<ArticleItem> page, HttpServletResponse response)
			throws Exception {
		Workbook workbook = ExcelGenerate.excelWrite(setExcelContent(page));
		response.setContentType("application/vnd.ms-excel");
		WebUtils.setDownloadableHeader(response, "articleItem.xls");
		workbook.write(response.getOutputStream());
		response.getOutputStream().flush();
	}

	private Excel setExcelContent(Page<ArticleItem> page) {
		Excel excel = new ExcelGenerate().new Excel();
		excel.setTitle("文章目录");
		List<ExcelRow> listRow = new LinkedList<ExcelRow>();
		String[] title = new String[] { "文章类型","文章标题", "创建人", "创建日期" };
		ExcelRow row =  new ExcelGenerate().new ExcelRow(title);
		listRow.add(row);
		for (ArticleItem articleItem : page.getResult()) {
			ExcelRow row2 = new ExcelGenerate().new ExcelRow();
			List<ExcelCell> list=new LinkedList<ExcelCell>();
			list.add(new ExcelGenerate().new ExcelCell(articleItem.getArticle().getArticletype()));
			list.add(new ExcelGenerate().new ExcelCell(articleItem.getTitle()));
			list.add(new ExcelGenerate().new ExcelCell("admin"));
			list.add(new ExcelGenerate().new ExcelCell(new DateTime(articleItem.getInsertDate()== null ? (new DateTime()) : articleItem.getInsertDate()).toString("YYYY-MM-dd"),
							ExcelGenerate.DATE));
			row2.setExcelCells(list);
			listRow.add(row2);
		}
		excel.setExcelRows(listRow);
		return excel;
	}

	/*
	 * 生成Pdf报表
	 */
	public void getPdf(Page<ArticleItem> page, HttpServletResponse response)
			throws Exception {
		PdfGenerate pdfGenerate = new PdfGenerate();
		PdfRow pdfRow = pdfGenerate.new PdfRow();
		pdfRow.setPdfTitle("文章目录");
		pdfRow.setPdfOther("文章目录");
		List<Object[]> content = new ArrayList<Object[]>();
		String[] title = new String[] { "文章类型","文章标题", "创建人", "创建日期" };
		content.add(title);
		for (ArticleItem o : page.getResult()) {
			List<String> list = new ArrayList<String>();
			list.add(o.getArticle().getArticletype());
			list.add(o.getTitle());
			list.add("admin");
			list.add(new DateTime(o.getInsertDate()== null ? (new DateTime()) : o.getInsertDate()).toString("YYYY-MM-dd"));
			content.add(list.toArray());
		}
		pdfRow.setContent(content);
		float[] widths = { 15f, 55f, 15f, 15f };
		response.setContentType("application/pdf");
		WebUtils.setDownloadableHeader(response, "articleItem.pdf");
		response = PdfGenerate.pdfWrite(pdfRow, widths, response);
		response.getOutputStream().flush();
	}
}
